import axios from "axios";
import ElementUI from 'element-ui'  //用于显示弹窗
import router from "@/router";
import store from "@/store";
import config from "@/config";

axios.defaults.baseURL=config.baseURL   //访问后端的基础url

//发起请求时拦截
axios.interceptors.request.use(request=>{
    request.headers['Authorization']=localStorage.getItem("token") //每次请求都附带上jwt
    return request;
})

//得到响应时拦截
axios.interceptors.response.use(response=>{
    if(response.data.code == 200){
        return response;
    }else {
        ElementUI.Message.error(response.data.msg,{duration:3000})
        return Promise.reject(response.data.msg)    //结束本次响应
    }
},
error => {  //400状态码会走这里
    if(error.response.data.path != '/loginbytoken'){
        store.commit('reset_data')
        store.commit('set_needLogin',true)
        //ElementUI.Message.error("登录认证已过期，请重新登陆",{duration:3000})
    }
    return Promise.reject(error)    //结束本次响应
})

export default axios;
